package com.sann.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sann.common.utils.CommonUtil;
import com.sann.common.utils.JwtUtil;
import com.sann.common.utils.MD5;
import com.sann.common.utils.ResultCode;
import com.sann.servicebase.handler.exception.GuliException;
import com.sann.user.entity.Member;
import com.sann.user.entity.vo.RegisterVo;
import com.sann.user.mapper.MemberMapper;
import com.sann.user.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-05-24
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 注册的方法
    @Override
    public void register(RegisterVo vo) {
        // 非空检查
        String code = vo.getCode(); //验证码
        String mobile = vo.getMobile(); //手机号
        String nickname = vo.getNickname(); //昵称
        String password = vo.getPassword(); //密码

//        CommonUtil.checkNotNull(code, "验证码");
        if (StringUtils.isBlank(code)) {
            throw new GuliException(ResultCode.ERROR, "验证码不能为空");
        }
        if (StringUtils.isBlank(mobile)) {
            throw new GuliException(ResultCode.ERROR, "手机号码不能为空");
        }
        if (StringUtils.isBlank(nickname)) {
            throw new GuliException(ResultCode.ERROR, "昵称不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new GuliException(ResultCode.ERROR, "密码不能为空");
        }


        // 判断验证码: 获取redis验证码
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if (!code.equals(redisCode)) {
            throw new GuliException(ResultCode.ERROR, "验证码无效");
        }

        // 判断手机号是否重复，表里面存在相同手机号不进行添加
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0) {
            throw new GuliException(ResultCode.ERROR, "手机号码已存在");
        }

        //数据添加数据库中
        Member member = new Member();
        member.setMobile(mobile);
        member.setNickname(nickname);
        member.setPassword(MD5.encrypt(password));// 保存加密密码
        member.setIsDisabled(false);
        baseMapper.insert(member);
    }

    // 登录的方法
    @Override
    public String login(Member member) {
        //获取登录手机号和密码
        String mobile = member.getMobile();
        String password = member.getPassword();

        //手机号和密码非空判断
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)) {
            throw new GuliException(ResultCode.ERROR, "登录失败");
        }

        //判断手机号是否正确
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        Member mobileMember = baseMapper.selectOne(wrapper);
        //判断查询对象是否为空
        if (mobileMember == null) {
            log.error("{}", "该手机号码还未在系统中注册");
            throw new GuliException(ResultCode.ERROR, "登录失败");
        }

        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据库密码进行比较
        //加密方式 MD5
        if (!MD5.encrypt(password).equals(mobileMember.getPassword())) {
            log.error("{}", "密码不正确");
            throw new GuliException(ResultCode.ERROR, "登录失败");
        }

        //判断用户是否禁用
        if (mobileMember.getIsDisabled()) {
            log.error("{}", "用户状态锁定");
            throw new GuliException(ResultCode.ERROR, "登录失败");
        }

        //登录成功, 返回token
        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtil.getJwtToken(mobileMember.getId(), mobileMember.getNickname());
        return jwtToken;
    }

    @Override
    public Member getOpenIdMember(String openid) {
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        Member member = baseMapper.selectOne(wrapper);
        return member;
    }


    public static void main(String[] args) {
        String str = "111111";
        String zjw = MD5.encrypt(str);
        System.out.println(zjw);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            String hashPwd = new BigInteger(1, md5.digest()).toString(16);
            System.out.println(hashPwd);

            String s = DigestUtils.md5DigestAsHex(str.getBytes());
            System.out.println(s);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
